<?php

namespace app\controller;

use DateTime;
use support\Request;
use app\model\BlogArticle;

class ArticleController
{
    /**
     * 文章详情
     */
    public function detail(Request $request, int $id)
    {
        if ($id <= 0) {
            return response('错误的请求!', 400);
        }
        $article = BlogArticle::where('id', $id)->first()->toArray();
        return view('article/detail', ['article' => $article]);
    }

    /**
     * 搜索文章
     */
    public function search(Request $request)
    {
        $keyword = $request->get('keyword');
        if (!$keyword) {
            return response('错误的请求!', 400);
        }
        $articles = BlogArticle::where('title', 'like', "%{$keyword}%")->get()->toArray();
        return view('article/search', ['keyword' => $keyword, 'articles' => $articles]);
    }

    /**
     * 文章归档
     */
    public function archive(Request $request)
    {
        $archives = [];
        $years = [];    // 所有年份列表
        $articles = BlogArticle::select(['id', 'title', 'cate_name', 'created_at'])->get()->toArray();
        foreach ($articles as $article) {
            // 获取年份
            $year = (int) (new DateTime($article['created_at']))->format('Y');
            if (!in_array($year, $years)) {
                array_push($years, $year);
            }
        }

        foreach ($years as $year) {
            $temp = ['year' => $year, 'articles' => []];
            foreach ($articles as $article) {
                if ((int) (new DateTime($article['created_at']))->format('Y') == $year) {
                    array_push($temp['articles'], $article);
                }
            }

            array_push($archives, $temp);
        }

        return view('article/archive', ['archives' => $archives]);
    }
}